/*
 * This code is property of BrightSky, Inc. Use, duplication and disclosure
 * in any form without permission of copyright holder is prohibited.
 *
 * (C) Copyright BrightSky, Inc. 2011. All rights reserved.
 */
package com.teachlearnweb.mvc.controller;

import java.io.IOException;
import java.util.Locale;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.RenderResponse;
import javax.portlet.ResourceRequest;
import javax.portlet.ResourceResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.portlet.bind.annotation.ActionMapping;
import org.springframework.web.portlet.bind.annotation.RenderMapping;
import org.springframework.web.portlet.bind.annotation.ResourceMapping;

import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.util.PortalUtil;

/**
 * The Class RegistrationController, is responsible to handle the user
 * registration request.
 * @author asharma
 * @author arvindk
 */
@Controller("registrationController")
@RequestMapping(value = "VIEW")
public class RegistrationController extends AbstractBaseController {

    /** The LOG. */
    private static final Log LOG = LogFactory
            .getLog(RegistrationController.class);

    /** The errormsg key. */
    private static final String ERROR_MSG_KEY = "errormsg";

    /** The registration validator. */
    @Autowired
    @Qualifier("registrationValidator")
    private transient Validator registrationValidator;

    /**
     * Show registration.
     * @param renderResponse
     *            the render response
     * @return the string
     */
    @RenderMapping
    public String showRegistration(RenderResponse renderResponse) {
        return "registration";
    }

    /**
     * Gets the command object.
     * @return the command object
     */
   /* @ModelAttribute("registrationModelBean")
    public RegistrationModelBean getCommandObject() {
        LOG.debug("Creating object of model RegistrationModelBean..");
        RegistrationModelBean registrationModelBean = new RegistrationModelBean();
        FaceBookService facebookService = serviceLocator.getFaceBookService();
        registrationModelBean.setFacebookCancelUrl(facebookService
                .getOnCancelRedirectionUrl());
        return registrationModelBean;
    }*/

    /**
     * Show captcha image for user to verify.
     * @param resourceRequest the resource request
     * @param resourceResponse the resource response
     * @throws IOException Signals that an I/O exception has occurred.
     */
    /*@ResourceMapping(value = "showCaptchaText")
    public void showCaptchaText(ResourceRequest resourceRequest,
            ResourceResponse resourceResponse) throws IOException {
        LOG.debug("Showing Captcha Image..");

        HttpServletRequest request = WebUtil
                .getHttpServletRequest(resourceRequest);
        String sessionId = request.getSession().getId();
        Locale locale = request.getLocale();
        byte[] captchaAsJpeg = CaptchaService.getCaptchaChallenge(sessionId,
                locale);

        resourceResponse.setContentType("image/jpeg");
        resourceResponse.getPortletOutputStream().write(captchaAsJpeg);
        resourceResponse.getPortletOutputStream().flush();
        resourceResponse.getPortletOutputStream().close();
    }*/

    /**
     * Submit registration.
     * @param registrationBean
     *            the registration model bean
     * @param bindingResult
     *            the binding result
     * @param actionRequest
     *            the request
     * @param actionResponse
     *            the response
     * @param sessionStatus
     *            the session status
     */
   /* @ActionMapping(params = "action=doRegistration")
    public void doRegistration(
            @ModelAttribute RegistrationModelBean registrationBean,
            BindingResult bindingResult, ActionRequest actionRequest,
            ActionResponse actionResponse, SessionStatus sessionStatus) {
        LOG.debug("Request received to register the user...");

        HttpServletRequest request = WebUtil
                .getHttpServletRequest(actionRequest);
        registrationBean.setShowError(false);

        boolean isValid = validate(request, registrationBean, bindingResult);

        if (isValid) {
            UserDetails userDetails = new UserDetails();
            long companyId = PortalUtil.getCompanyId(request);
            try {
                populateDomainObject(registrationBean, userDetails);
                // Register the user with company.
                boolean isRegistered = registerUser(registrationBean,
                        userDetails, companyId);
                registrationBean.setSuccess(isRegistered);

                registrationBean.setShowForm(Boolean.FALSE);
            } catch (BusinessException bizExp) {
                LOG.error("Business Exception while registration."
                        + bizExp.getStackTrace());
                resetFields(registrationBean);
                bindingResult.rejectValue(ERROR_MSG_KEY, bizExp.getErrorCode());
            } catch (Exception exp) {
                LOG.error("Exception while registration.", exp);
                resetFields(registrationBean);
                bindingResult.rejectValue(ERROR_MSG_KEY,
                        ErrorCodes.SYSTEM_FAILED_REGISTRATION);
            }
        }
    }
*/
    /**
     * Reset fields.
     * @param registrationModelBean the registration model bean
     */
  /*  private void resetFields(RegistrationModelBean registrationModelBean) {
        registrationModelBean.setStrJCaptcha("");
        registrationModelBean.setShowError(Boolean.TRUE);
    }
*/
    /**
     * Register user.
     * @param registrationBean the registration bean
     * @param userDetails the user details
     * @param companyId the company id
     * @return true, if successful
     * @throws PortalException the portal exception
     * @throws SystemException the system exception
     * @throws BusinessException the business exception
     */
   /* private boolean registerUser(RegistrationModelBean registrationBean,
            UserDetails userDetails, long companyId) throws PortalException,
        SystemException, BusinessException {

        UserRegistrationService service = serviceLocator
                .getUserRegistrationService();
        if (registrationBean.getRole().equalsIgnoreCase(
                RoleType.PATIENT.getRole())) {
            service.registerPatient(userDetails, companyId);
        } else if (registrationBean.getRole().equalsIgnoreCase(
                RoleType.CAREGIVER.getRole())) {
            service.registerCareGiver(userDetails, companyId);
        } else if (registrationBean.getRole().equalsIgnoreCase(
                RoleType.HEALTHCAREPROFESSIONALS.getRole())) {
            service.registerPhysician(userDetails, companyId);
        } else if (registrationBean.getRole().equalsIgnoreCase(
                RoleType.HEALTHPLAN.getRole())) {
            service.registerCareGiver(userDetails, companyId);
        }
        return Boolean.TRUE;
    }*/

    /**
     * Populate domain from form bean.
     * @param registrationBean the registration model bean
     * @param userDetails the user details
     * @param actionRequest the action request
     */
   /* private void populateDomainObject(RegistrationModelBean registrationBean,
            UserDetails userDetails) {
        LOG.debug("Populating domain object from registration model bean.");
        userDetails.setFirstname(registrationBean.getFirstName().trim());
        userDetails.setLastname(registrationBean.getLastName().trim());
        userDetails.setEmail(registrationBean.getEmailAddress());
        userDetails.setPassword(registrationBean.getPassword());
        userDetails.setConfirmPassword(registrationBean.getConfirmPassword());

        // DOB & Gender is only applicable to Patient
        if (registrationBean.getRole().equalsIgnoreCase(
                RoleType.PATIENT.getRole())) {
            String dob = registrationBean.getDob();
            userDetails.setDateOfBirth(DateUtils.convertStringToCalendar(dob,
                    PortletConstants.BIRTHDATE_FORMAT));

            if ("F".equalsIgnoreCase(registrationBean.getGender())) {
                userDetails.setMale(false);
            }
        } else {
            userDetails.setDateOfBirth(DateUtils.getDummyDate());
        }
    }*/

    /**
     * Validate.
     * @param request the request
     * @param registrationBean the registration bean
     * @param bindingResult the binding result
     * @return true, if successful
     */
    /*private boolean validate(HttpServletRequest request,
            RegistrationModelBean registrationBean, BindingResult bindingResult) {
        boolean isValid = Boolean.FALSE;
        boolean isCaptchaValid = Boolean.TRUE;

        registrationValidator.validate(registrationBean, bindingResult);

        if (!bindingResult.hasErrors()) {
            isCaptchaValid = validateCaptcha(request,
                    registrationBean.getStrJCaptcha());
            if (!isCaptchaValid) {
                bindingResult.rejectValue(ERROR_MSG_KEY,
                        "error.captcha.invalid");
                registrationBean.setShowError(Boolean.TRUE);
            }
        }

        if (isCaptchaValid && !bindingResult.hasErrors()) {
            isValid = Boolean.TRUE;
        } else {
            registrationBean.setStrJCaptcha("");
        }
        return isValid;
    }
*/
    /**
     * Validate captcha.
     * @param request the http servlet request
     * @param captchaText the str response
     * @return true, if successfully validated
     */
    /*private Boolean validateCaptcha(HttpServletRequest request,
            String captchaText) {
        LOG.debug("Validating Captcha Image..");
        String sessionId = request.getSession().getId();

        Boolean isCaptchaValid = CaptchaService
                .validate(sessionId, captchaText);
        return isCaptchaValid;
    }*/
}
